package cz.uhk.ppro.services;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import cz.uhk.ppro.entities.Uzivatel;

@Transactional
public class PasswordService {
	private byte[] bytes;
	private String result;

	@PersistenceContext
	EntityManager em;
	
	public PasswordService() {
		
	}
	
	public Uzivatel getUzivIndex(int index){
		return (Uzivatel)(em.createQuery("from Uzivatel").getResultList()).get(index);
	}
	
	public Uzivatel getdleId(int id){
		return em.find(Uzivatel.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public String check(String login, String pass) throws Exception{
		bytes = pass.getBytes();
		cryptMd5();
		List<Uzivatel> seznamUziv = em.createQuery("from Uzivatel").getResultList();
		for (Uzivatel u : seznamUziv) {
			if (u.getLogin().compareTo(login)== 0 
					&& u.getHeslo().compareTo(result)==0) {
					return u.getSkupina();
			}
		}
		return "fail";
	}
	
	public String setBytes(String input) throws Exception{
		bytes = input.getBytes();
		cryptMd5();
		return result;
	}
	
	private void cryptMd5() throws Exception {
		MessageDigest MD5 = null 	;
		try {
			MD5 = MessageDigest.getInstance("md5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		MD5.update(bytes);
		byte[] hash = MD5.digest();
		getHexString(hash);
	}
		
	public void getHexString(byte[] b) throws Exception {
		result = "";
		for (int i = 0; i < b.length; i++) {
			result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
		}
	}
}
